﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EqRepair.Code.Classes;
using EqRepair.Code.Data;

namespace EqRepair.Web
{
	public partial class ProcessRequest : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			AccessData.CreateAutoReq();
			using (var db = new DataClasses2DataContext())
			{
				PanelOrd.Visible = false;
				PanelReqMod.Visible = false;
				LabelMes.Text = "";
				Info.Text = "";
				ButtonOrdFin.Visible = false;
				updateReq();
				
			}
		}

		protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		protected void LinqDataSource3_Selecting(object sender, LinqDataSourceSelectEventArgs e)
		{

		}

		protected void ButtonSelOrg_Click(object sender, EventArgs e)
		{
			if (DropDownListOrg.SelectedItem != null)
			{
				Session["curOrg"] = DropDownListOrg.SelectedItem.Value;
				Panel1.Visible = false;
				updateReq();
			}
			
		}

		protected void ButtonSelAl_Click(object sender, EventArgs e)
		{
			Session["curOrg"] = "ALL";
            Panel1.Visible = false;
			updateReq();
		}
		public void updateOrd()
		{
			using (var db = new DataClasses2DataContext())
			{
				if (GridView1.SelectedIndex >= 0 && GridView1.SelectedIndex < GridView1.Rows.Count && GridView1.SelectedRow != null)
				{
					GridViewOrd.DataSource = null;
					PanelOrd.Visible = false;
					int idR = Int32.Parse(GridView1.SelectedRow.Cells[1].Text);
					if (db.DetachmentRepairs.Where(x => x.RequestId == idR).Count() > 0)
					{
						PanelOrd.Visible = true;
						GridViewOrd.DataSource = null;
						GridViewOrd.DataSource = from lnk in db.DetachmentRepairs
												 where (lnk.RequestId == idR)
												 select new
														 {
															 lnk.Id,
															 lnk.RequestId,
															 lnk.Employee.FullName,
															 lnk.Status,
                                                             lnk.Descr
														 };
						GridViewOrd.DataBind();
					}

					PanelReqMod.Visible = true;

					int Curuser = new SessionAuthentification(Session).GetCurrentUserID();
					
				}
				else
				{
					GridViewOrd.DataSource = null;
					GridViewOrd.DataBind();
				}
			}
		}
		public void updateReq()
		{
			using (var db = new DataClasses2DataContext())
			{
                Panel1.Visible = false;
				int Curuser = new SessionAuthentification(Session).GetCurrentUserID();
				IQueryable JoinQuery;
				if (Session["curOrg"] != null)
				{
					var t = Session["curOrg"];
					if (Session["curOrg"].ToString() == "ALL")
					{
						JoinQuery =
							from lnk in db.RequestForRepairs
							join EqOrg in db.EquipmentInOrganizations on lnk.EquipmentInOrganization equals EqOrg
							join Eq in db.Equipments on EqOrg.Equipment equals Eq

							join Organ in db.Organizations on EqOrg.Organization equals Organ
							where (lnk.CreatedById == Curuser || lnk.CreatedById == AccessData.GetSystemID())
							/* ||(lnk.CreatedById == AccessData.GetChiefCurUser(Curuser))*/
							select
								new
									{
										lnk.Id,
										lnk.Employee.FullName,
										lnk.Status,
										lnk.CreatedDateTime,
										Organize = Organ.Name,
										equipment = Eq.Name,
										Eq.RepairCost,
										Eq.RepairTime,
                                        lnk.Descr
									};
					}
					else
					{
					    JoinQuery =
					        from lnk in db.RequestForRepairs
					        join EqOrg in db.EquipmentInOrganizations on lnk.EquipmentInOrganization equals EqOrg
					        join Eq in db.Equipments on EqOrg.Equipment equals Eq

					        join Organ in db.Organizations on EqOrg.Organization equals Organ
					        where
					            ((lnk.CreatedById == Curuser || lnk.CreatedById == AccessData.GetSystemID()) &&
					             (EqOrg.OrganizationId == Int32.Parse(Session["curOrg"].ToString())))
					        select
					            new
					                {
					                    lnk.Id,
					                    lnk.Employee.FullName,
					                    lnk.Status,
					                    lnk.CreatedDateTime,
					                    Organize = Organ.Name,
					                    equipment = Eq.Name,
					                    Eq.RepairCost,
					                    Eq.RepairTime,
					                    lnk.Descr
									};

					}
					GridView1.DataSource = JoinQuery;
					GridView1.DataBind();
					updateOrd();
				}
			}
		}

		protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
		{
			using (var db = new DataClasses2DataContext())
			{
                Panel1.Visible = true;
				updateOrd();
				if (DropDownListEmpl.DataSource == null)
				{
                    TextBoxDes.Text = "";
					int Curuser = new SessionAuthentification(Session).GetCurrentUserID();
					DropDownListEmpl.DataSource = db.Employees.Where(x => x.ChiefId == Curuser);
					DropDownListEmpl.DataTextField = "FullName";
					DropDownListEmpl.DataValueField = "Id";
					DropDownListEmpl.DataBind();
				}
			}
		}

		protected void ButtonClose_Click(object sender, EventArgs e)
		{
			if (GridView1.SelectedRow != null)
			{
				using (var db = new DataClasses2DataContext())
				{
					int Curuser = new SessionAuthentification(Session).GetCurrentUserID();
					int idR = Int32.Parse(GridView1.SelectedRow.Cells[1].Text);
					db.RequestForRepairs.First(x => x.Id == idR).Status = 4;
					db.SubmitChanges();

					updateReq();
					
					LabelMes.Text = "Заявка №" + idR + " закрыта.";
				}
			}
		}

		protected void ButtonCrOr_Click(object sender, EventArgs e)
		{
			int Em;
			if (Session["SelE"]!=null)
			{
				Em = Int32.Parse(Session["SelE"].ToString());
			}
			else
				Em= Int32.Parse(DropDownListEmpl.SelectedValue);
			using (var db = new DataClasses2DataContext())
			{

				int idR = Int32.Parse(GridView1.SelectedRow.Cells[1].Text);
				int s = db.RequestForRepairs.First(x => x.Id == idR).Status;
				if (s != 3 && s != 4)
				{
					db.RequestForRepairs.First(x => x.Id == idR).Status = 2;
					db.SubmitChanges();
					GridView1.DataBind();
					int Curuser = new SessionAuthentification(Session).GetCurrentUserID();
					var dr = new DetachmentRepair
					         	{
					         		ResponsibleId = Em,
					         		RequestId = idR,
					         		Status = 2,
                                    Descr = TextBoxDes.Text
					         	};
					db.DetachmentRepairs.InsertOnSubmit(dr);
					db.SubmitChanges();
					updateReq();
					updateOrd();
				}
				else
					LabelMes.Text = "Заявка №" + idR + " закрыта. Создать наряд нельзя.";
			}
		}

		protected void ButtonOrdFin_PreRender(object sender, EventArgs e)
		{
			
		}

		protected void ButtonOrdFin_Click(object sender, EventArgs e)
		{
			if (GridViewOrd.SelectedIndex >= 0 && GridViewOrd.SelectedIndex < GridViewOrd.Rows.Count && GridView1.SelectedRow != null)
			{
				string inf="";
				using (var db = new DataClasses2DataContext())
				{
					int idO = Int32.Parse(GridViewOrd.SelectedRow.Cells[1].Text);
					if (db.DetachmentRepairs.First(x => x.Id == idO).Status != 3)
					{
						db.DetachmentRepairs.First(x => x.Id == idO).Status = 3;
						db.SubmitChanges();
						if (
							db.DetachmentRepairs.First(x => x.Id == idO).RequestForRepair.DetachmentRepairs.Where(x => x.Status != 3).Count() ==
							0)
						{
							db.DetachmentRepairs.First(x => x.Id == idO).RequestForRepair.Status = 3;
							db.DetachmentRepairs.First(x => x.Id == idO).RequestForRepair.EquipmentInOrganization.LastRepairDate =
								DateTime.Now;
							inf = "Все работы выполнены. Заявка № " + db.DetachmentRepairs.First(x => x.Id == idO).RequestForRepair.Id +
								  " закрыта.";
						}
						db.SubmitChanges();
						updateReq();
						updateOrd();
						Info.Text = inf;
					}
					else
						Info.Text = "Наряд уже выполнен.";
				}
			}
		}

		protected void GridViewOrd_SelectedIndexChanged(object sender, EventArgs e)
		{
			ButtonOrdFin.Visible = true;
		}

		protected void DropDownListEmpl_SelectedIndexChanged(object sender, EventArgs e)
		{
			Session["SelE"] = DropDownListEmpl.SelectedValue;
		}
	}
}
	
